package org.sith.taskrunner.ejb.transformers;

import org.sith.taskrunner.api.transformer.InputDataTransofrmer;
import org.sith.taskrunner.api.exceptions.TransformInputDataException;
import org.sith.taskrunner.ejb.tasks.SumInputData;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class StringSumDataTransformer implements
        InputDataTransofrmer<SumInputData, String> {
	/**
	 * Transform string with integers to SumInputData
	 * 
	 * @param inputData
	 * @return SumInpudata instance
	 * @throws TransformInputDataException
	 */
	@Override
	public SumInputData transform(String inputData)
			throws TransformInputDataException {
		List<Integer> numbers = new ArrayList<Integer>();
		StringTokenizer st = new StringTokenizer(inputData, " ");
		String lastToken;
		while (st.hasMoreTokens()) {
			lastToken = st.nextToken();
			Integer number;
			try {
				number = Integer.parseInt(lastToken);
			} catch (NumberFormatException e) {
				throw new TransformInputDataException(
						"Your input data is not valid: " + inputData
								+ ". Only doubles allowed", e);
			}
			numbers.add(number);
		}

		return new SumInputData(numbers);
	}
}
